<template>
  <div class="init-container">
    <div class="mask-container" v-if="isMask"></div>
    <div class="auto-data-query">
      <!-- 左侧查询栏 -->
      <div class="query-panel">
        <Form :model="queryParams" label-position="top">
          <FormItem label="查询日期范围">
            <DatePicker
              v-model="queryParams.dateRange"
              type="daterange"
              :options="dateOptions"
              style="width: 100%"
            />
          </FormItem>
          <FormItem label="工作日数">
            <InputNumber
              v-model="queryParams.workDays"
              :min="1"
              :max="maxWorkDays"
            />
          </FormItem>
          <FormItem>
            <Button type="primary" @click="handleQuery">查询</Button>
            <Button style="margin-left: 10px" @click="handleReset">重置</Button>
          </FormItem>
        </Form>
      </div>

      <!-- 右侧表格 -->
      <div class="table-panel">
        <vxe-toolbar>
          <template #buttons>
            <vxe-button icon="fa fa-upload" @click="handleUpload">
              上传数据
            </vxe-button>
          </template>
        </vxe-toolbar>

        <vxe-table class="table" :data="tableData" show-overflow border>
          <vxe-column
            v-for="col in tableColumns"
            :key="col.field"
            :field="col.field"
            :title="col.title"
          />
        </vxe-table>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import {
  tableColumns,
  formConfig,
  Tsrv,
  T_srv,
  ifs,
  ts,
  vue,
  I_cmd,
  T_cmd,
  N_cAutoDataQuery
} from './config';

@T_srv.comp
export default class cAutoDataQuery extends vue {
  /* 指挥部 */
  private GT_command: I_cmd = new T_cmd();

  /* 遮罩 */
  public isMask: boolean = false;

  // 查询参数
  private queryParams: N_cAutoDataQuery.QueryParams = {
    dateRange: formConfig().dateRange.default,
    workDays: formConfig().workDays.default
  };

  // 表格配置
  private tableColumns = tableColumns();

  // 表格数据
  private tableData: N_cAutoDataQuery.TableDataItem[] = [];

  // 获取最大工作日数
  get maxWorkDays(): number {
    return this.GT_command.calculateWorkDays(
      this.queryParams.dateRange[0],
      this.queryParams.dateRange[1]
    );
  }

  // 日期选择器选项
  private dateOptions = {
    disabledDate(date: Date) {
      return date && date.valueOf() > Date.now();
    }
  };

  async created() {
    this.GT_command.init(this);
    try {
      await this.handleQuery();
    } catch (error) {
      this.$Message.error('初始化查询失败');
      console.error(error);
    }
  }

  // 查询处理
  async handleQuery() {
    try {
      if (
        !this.GT_command.validateWorkDays(
          this.queryParams.workDays,
          this.queryParams.dateRange
        )
      ) {
        this.$Message.error('工作日数不能超过查询日期范围的天数');
        return;
      }
      this.isMask = true;
      this.tableData = await this.GT_command.generateTableData(
        this.queryParams
      );
    } catch (error) {
      this.$Message.error('查询数据失败');
      console.error(error);
    } finally {
      this.isMask = false;
    }
  }

  // 重置处理
  async handleReset() {
    this.queryParams = {
      dateRange: formConfig().dateRange.default,
      workDays: formConfig().workDays.default
    };
    try {
      await this.handleQuery();
    } catch (error) {
      this.$Message.error('重置查询失败');
      console.error(error);
    }
  }

  private handleUpload() {
    this.$Modal.confirm({
      title: '上传数据',
      content: '确定上传当前查询结果数据？',
      onOk: async () => {
        try {
          const result = await this.GT_command.uploadData(
            this.tableData,
            this.queryParams
          );
          if (result.success) {
            this.$Message.success(result.message);
            // 新增上传记录
            this.insertData();
          } else {
            this.$Message.error(result.message);
          }
        } catch (error) {
          this.$Message.error(`上传失败: ${error.message}`);
        }
      },
      onCancel: () => {}
    });
  }

  private insertData() {
    const ctd = new ts.T_ctdArg();
    const data = this.tableData[0];
    const row = [
      {
        field: 'unit_order_execution_time',
        value: data.execTime
      } as ifs.I_fv,
      {
        field: 'total_work_time',
        value: data.totalWorkTime
      } as ifs.I_fv,
      {
        field: 'utilization',
        value: data.utilization
      } as ifs.I_fv,
      {
        field: 'auto_orders',
        value: data.autoOrders
      } as ifs.I_fv,
      {
        field: 'total_orders',
        value: data.totalOrders
      } as ifs.I_fv,
      {
        field: 'auto_order_rate',
        value: data.autoRate
      } as ifs.I_fv,
      {
        field: 'upload_date',
        value: data.evalPeriod
      } as ifs.I_fv,
      {
        field: 'auto_racks',
        value: data.autoRacks
      } as ifs.I_fv,
      {
        field: 'total_racks',
        value: data.totalracks
      } as ifs.I_fv,
      {
        field: 'auto_rack_rate',
        value: data.autoRackRate
      } as ifs.I_fv
    ];
    ctd
      .setTableName('auto_data_upload_record')
      .setDbType(Tsrv.globalVar.dbType.MYSQL)
      .setRule({} as ifs.I_rule);
    const baseData = new ts.T_baseData();
    baseData
      .setDataRule({} as ifs.I_rule)
      .setFileInfo({})
      .setRowData(...row);
    ctd.setInsRecDataOne({}, {} as ifs.I_rule, {}, ...row);
    Tsrv.batRows(ctd).then(([b, res, msg]) => {
      if (!b) {
        this.$msg(msg);
      }
    });
  }
}
</script>

<style lang="scss" scoped>
.auto-data-query {
  display: flex;
  height: 100%;

  .query-panel {
    width: 300px;
    padding: 20px;
    border-right: 1px solid #dcdee2;
  }

  .table-panel {
    flex: 1;
    padding: 20px;
    overflow: auto;
    height: 100%;
    .table {
      height: calc(100% - 50px);
      ::v-deep .vxe-table--render-wrapper {
        height: 100%;
      }
    }
  }
}
</style>
